<?php

class SubstituteModelDao {
	
	function SubstituteModelDao() {
	}

	function getSubstitutesForMatch($id_match, $is_visitor) {
		$sub = array();
		$nbrecord=0;
		$query  = "SELECT S.ID_PLAYER_IN, S.ID_PLAYER_OUT, S.TIME, ";
		$query .= "PI.FIRST_NAME AS IN_FIRST_NAME, PI.LAST_NAME AS IN_LAST_NAME, "; 
		$query .= "PO.FIRST_NAME AS OUT_FIRST_NAME, PO.LAST_NAME AS OUT_LAST_NAME "; 
		$query .= "FROM TBL_SUBSTITUTIONS S ";
		$query .= "INNER JOIN TBL_PLAYER PI ON PI.ID_PLAYER=S.ID_PLAYER_IN ";
		$query .= "INNER JOIN TBL_PLAYER PO ON PO.ID_PLAYER=S.ID_PLAYER_OUT ";
		$query .= "WHERE S.ID_MATCH=$id_match AND S.IS_VISITOR=$is_visitor ORDER BY TIME";
		$result = mysql_query ($query) or trigger_error(mysql_error(), E_USER_ERROR);
		while ($row = mysql_fetch_assoc($result)) {
			$sub[] = new SubstituteModel($row);
			$nbrecord++;
		}
		return $sub;
	}
    
	function addSubstituteForMatch($id_match, $id_sub_in, $is_sub_out, $time_sub, $is_visitor) {
		$query  = "INSERT INTO TBL_SUBSTITUTIONS (ID_MATCH, ID_PLAYER_IN, ID_PLAYER_OUT, TIME, IS_VISITOR) ";
		$query .= "VALUES($id_match, $id_sub_in, $is_sub_out, $time_sub, $is_visitor)";
		
		mysql_query($query) or trigger_error(mysql_error(), E_USER_ERROR);
		
	}
	
	function deleteSubstitutionsForMatch($id_match) {
		$query = "DELETE FROM TBL_SUBSTITUTIONS WHERE ID_MATCH=$id_match";
		mysql_query($query) or trigger_error(mysql_error(), E_USER_ERROR);
	}
	
	function setPlayTime($id_match,$matchplayer) {
		$match_tot_time = 90;
		
	
		$id_player=$matchplayer->getId_player();
		$num=$matchplayer->getNumPlayer();
		if($num>=12) {
			$time_player=0;
		}
		else {
			$time_player=$match_tot_time;
		}
		
		
		
		// Recherche des entrees
		$query = "SELECT TIME FROM TBL_SUBSTITUTIONS WHERE ID_MATCH=$id_match AND ID_PLAYER_IN=$id_player";
		$result = mysql_query($query) or trigger_error(mysql_error(), E_USER_ERROR);
		while ($row = mysql_fetch_assoc($result)) {
			$time_player+=$match_tot_time-$row['TIME'];
		}
		
		// Recherche des sorties
		$query = "SELECT TIME FROM TBL_SUBSTITUTIONS WHERE ID_MATCH=$id_match AND ID_PLAYER_OUT=$id_player";
		$result = mysql_query($query) or trigger_error(mysql_error(), E_USER_ERROR);
		while ($row = mysql_fetch_assoc($result)) {
			$time_player-=$match_tot_time-$row['TIME'];
		}
		
		$matchplayer->setPlayTime($time_player);
		
	}
	
}

?>
	